<template>
  <div class="data-management">


    <!-- 页面标题 -->
    <div class="page-header">

     <div>
          <h2 class="page-title">
            <el-icon><Document /></el-icon> 表内容管理
          </h2>
          <!-- <p class="page-description">
            当前区域：{{ route.query.region }}<br/>
            当前类别：{{ route.query.type }}<br/>
            当前表：{{ decodeURIComponent(route.params.tableName) }}
          </p> -->
          <p class="page-description">
            当前区域：{{ route.query.region }}<br/>
            当前类别：{{ route.query.type }}<br/>
            当前表：{{ thirdName }}
          </p>

        </div>

     <div>
          <!-- 返回编辑页卡片 -->
          <div class="back-card" @click="goBackToTablesPage">
            <el-icon class="back-icon"><ArrowLeft /></el-icon>
            <span class="back-text">返回所有表</span>
          </div>
      </div>
    </div>

    <!-- 高级搜索组件 -->
    <AdvancedSearch 
      ref="advancedSearchRef"
      :columns="columns"
      :table-name="tableName"
      @search="handleAdvancedSearch"
      @export="exportSearchResults"
    />

    <!-- 文件上传组件 -->
    <FileUpload 
      v-if="showFileUpload"
      @success="handleUploadSuccess"
      @refresh="refreshData"
    />

    <!-- 操作栏 -->
    <div class="action-bar">
      <div class="action-left">
        <el-button type="primary" @click="showCreateDialog = true">
          <el-icon><Plus /></el-icon>
          新增记录
        </el-button>
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
        <el-button type="success" @click="exportData">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
        <el-button 
          type="warning" 
          @click="toggleFileUpload"
          v-if="tableName === '建筑基础信息'"
        >
          <el-icon><Upload /></el-icon>
          文件导入
        </el-button>
        <el-upload
          v-else
          class="upload-demo"
          :show-file-list="false"
          :before-upload="beforeImport"
          accept=".json"
        >
          <el-button type="warning">
            <el-icon><Upload /></el-icon>
            导入数据
          </el-button>
        </el-upload>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="card-title">
            <el-icon><Memo /></el-icon>
            数据列表 (共 {{ total }} 条记录)
          </span>
          <div class="header-right">
            <span class="page-info">
              第 {{ currentPage }} 页，共 {{ Math.ceil(total / pageSize) }} 页
            </span>
          </div>
        </div>
      </template>
      
      <el-table 
        :data="tableData" 
        style="width: 100%" 
        v-loading="loading"
        :height="600"
      >
        <el-table-column
          v-for="column in displayColumns"
          :key="column.Field"
          :prop="column.Field"
          :label="column.Field"
          :min-width="getColumnWidth(column)"
          :sortable="column.sortable !== false"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <div class="cell-content">
              <span v-if="column.Type === 'tinyint(1)' || column.Type === 'boolean'">
                <el-tag :type="row[column.Field] ? 'success' : 'danger'">
                  {{ row[column.Field] ? '是' : '否' }}
                </el-tag>
              </span>
              <span v-else-if="column.Field === '坐标'">
                <el-tag type="primary" size="small" v-if="row[column.Field]">
                  {{ formatCoordinate(row[column.Field]) }}
                </el-tag>
                <el-tag type="info" size="small" v-else>未设置</el-tag>
              </span>
              <span v-else-if="isNumber(column.Type) && row[column.Field] !== null">
                {{ formatNumber(row[column.Field]) }}
              </span>
              <span v-else-if="isDate(column.Type) && row[column.Field]">
                {{ formatDate(row[column.Field]) }}
              </span>
              <span v-else-if="row[column.Field] === null || row[column.Field] === ''">
                <el-tag type="info" size="small">空</el-tag>
              </span>
              <span v-else>{{ row[column.Field] }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="editRecord(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="confirmDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingRecord ? '编辑记录' : '新增记录'"
      width="60%"
      :close-on-click-modal="false"
    >
      <el-form 
        ref="formRef" 
        :model="formData" 
        :rules="formRules" 
        label-width="120px"
        style="max-height: 500px; overflow-y: auto;"
      >
        <el-row :gutter="20">
          <el-col 
            v-for="column in editableColumns" 
            :key="column.Field"
            :span="getFormColSpan(column)"
          >
            <el-form-item 
              :label="column.Field" 
              :prop="column.Field"
              :required="column.Null === 'NO' && column.Extra !== 'auto_increment'"
            >
              <!-- 地理坐标输入 -->
              <div v-if="column.Field === '坐标'" class="coordinate-input">
                <div style="display: flex; gap: 8px; align-items: center;">
                  <el-input-number
                    v-model="formData.coordinate_lng"
                    placeholder="经度"
                    :precision="6"
                    :min="-180"
                    :max="180"
                    style="width: 120px;"
                  />
                  <span style="color: #909399;">经度</span>
                  <el-input-number
                    v-model="formData.coordinate_lat"
                    placeholder="纬度"
                    :precision="6"
                    :min="-90"
                    :max="90"
                    style="width: 120px;"
                  />
                  <span style="color: #909399;">纬度</span>
                </div>
                <div style="margin-top: 4px; font-size: 12px; color: #909399;">
                  示例：经度 116.1201，纬度 39.9401
                </div>
              </div>
              
              <!-- 布尔类型 -->
              <el-switch
                v-else-if="column.Type === 'tinyint(1)' || column.Type === 'boolean'"
                v-model="formData[column.Field]"
                active-text="是"
                inactive-text="否"
              />
              
              <!-- 枚举类型 -->
              <el-select
                v-else-if="column.Type.toUpperCase().startsWith('ENUM')"
                v-model="formData[column.Field]"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="option in getEnumOptions(column.Type)"
                  :key="option"
                  :label="option"
                  :value="option"
                />
              </el-select>
              
              <!-- 大文本 -->
              <el-input
                v-else-if="column.Type.toUpperCase().includes('TEXT')"
                v-model="formData[column.Field]"
                type="textarea"
                :rows="3"
                :placeholder="`请输入${column.Field}`"
              />
              
              <!-- 数字类型 -->
              <el-input-number
                v-else-if="column.Type.toUpperCase().includes('INT') || 
                          column.Type.toUpperCase().includes('DECIMAL') || 
                          column.Type.toUpperCase().includes('DOUBLE')"
                v-model="formData[column.Field]"
                style="width: 100%"
                :precision="getPrecision(column.Type)"
                :placeholder="`请输入${column.Field}`"
              />
              
              <!-- 日期时间 -->
              <el-date-picker
                v-else-if="column.Type.toUpperCase().includes('DATETIME') || 
                          column.Type.toUpperCase().includes('TIMESTAMP')"
                v-model="formData[column.Field]"
                type="datetime"
                placeholder="选择日期时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
              
              <!-- 日期 -->
              <el-date-picker
                v-else-if="column.Type.toUpperCase().includes('DATE')"
                v-model="formData[column.Field]"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
              
              <!-- 普通文本 -->
              <el-input
                v-else
                v-model="formData[column.Field]"
                :placeholder="`请输入${column.Field}`"
                :maxlength="getMaxLength(column.Type)"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="saveRecord" :loading="saveLoading">
          {{ editingRecord ? '更新' : '保存' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
// import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Document, Plus, Refresh, Download, Upload,
  Memo, Edit, Delete 
} from '@element-plus/icons-vue'
import { apiService } from '../api'
import AdvancedSearch from '../components/AdvancedSearch.vue'
import FileUpload from '../components/FileUpload.vue'
// import { ArrowLeft,Document } from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'



const router = useRouter()
const route = useRoute()
// const route = useRoute()
const tableName = computed(() => route.params.tableName)

const loading = ref(false)
const saveLoading = ref(false)
const showCreateDialog = ref(false)
const editingRecord = ref(null)
const advancedSearchRef = ref()
const showFileUpload = ref(false)

// 表格数据
const tableData = ref([])
const columns = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 当前搜索参数
const currentSearchParams = ref(null)

// 表单数据
const formData = reactive({})
const formRef = ref()

//顶部third三级表的过滤
const thirdName = computed(() => {
  const full = decodeURIComponent(route.params.tableName || '')
  const arr = full.split('_')
  return arr[arr.length - 1]
})


// 显示的列（排除过长的文本列），隐藏“所属区域”“表类型”“id”列
const displayColumns = computed(() => {
  return columns.value.filter(col => 
    !['LONGTEXT', 'BLOB'].some(type => col.Type.toUpperCase().includes(type))
    &&!['所属区域', '表类型', 'id'].includes(col.Field)
  )
})

// 可编辑的列（排除自增主键，隐藏“所属区域”“表类型”“id”列）
const editableColumns = computed(() => {
  return columns.value.filter(col => 
    !(col.Key === 'PRI' && col.Extra === 'auto_increment')
    &&!['所属区域', '表类型'].includes(col.Field)
  )
})

// 表单验证规则
const formRules = computed(() => {
  const rules = {}
  editableColumns.value.forEach(column => {
    if (column.Null === 'NO' && column.Extra !== 'auto_increment') {
      rules[column.Field] = [
        { required: true, message: `请输入${column.Field}`, trigger: 'blur' }
      ]
    }
  })
  return rules
})

// 获取列宽度
const getColumnWidth = (column) => {
  if (column.Type.includes('TEXT')) return 200
  if (column.Type.includes('VARCHAR')) {
    const match = column.Type.match(/\((\d+)\)/)
    if (match) {
      const length = parseInt(match[1])
      return Math.min(Math.max(length, 100), 300)
    }
  }
  if (isNumber(column.Type)) return 120
  if (isDate(column.Type)) return 150
  return 120
}

// 获取表单列宽
const getFormColSpan = (column) => {
  if (column.Type.toUpperCase().includes('TEXT')) return 24
  if (column.Field === '坐标') return 24
  return 12
}

// 类型判断函数
const isNumber = (type) => {
  return ['INT', 'BIGINT', 'DOUBLE', 'FLOAT'].some(t => 
    type.toUpperCase().includes(t)
  )
}

const isDate = (type) => {
  return ['DATE'].some(t => type.toUpperCase().includes(t))
}

const isCoordinate = (fieldName) => {
  return fieldName === '坐标'
}

// 格式化地理坐标
const formatCoordinate = (coordinate) => {
  if (!coordinate) return '未设置'
  
  // 处理对象格式坐标 {x: lng, y: lat}
  if (typeof coordinate === 'object' && coordinate.x !== undefined && coordinate.y !== undefined) {
    return `${parseFloat(coordinate.x).toFixed(4)}, ${parseFloat(coordinate.y).toFixed(4)}`
  }
  
  // 处理POINT格式：POINT(116.1201 39.9401)
  if (typeof coordinate === 'string') {
    // 处理POINT格式
    if (coordinate.includes('POINT')) {
      const match = coordinate.match(/POINT\(([^)]+)\)/)
      if (match) {
        const coords = match[1].split(' ')
        if (coords.length === 2) {
          return `${parseFloat(coords[0]).toFixed(4)}, ${parseFloat(coords[1]).toFixed(4)}`
        }
      }
    } 
    // 处理经纬度字符串格式："116.1201,39.9401"
    else if (coordinate.includes(',')) {
      const coords = coordinate.split(',').map(Number)
      if (coords.length === 2 && !isNaN(coords[0]) && !isNaN(coords[1])) {
        return `${coords[0].toFixed(4)}, ${coords[1].toFixed(4)}`
      }
    }
  }
  
  // 处理数字数组格式：[116.1201, 39.9401]
  if (Array.isArray(coordinate) && coordinate.length === 2) {
    return `${parseFloat(coordinate[0]).toFixed(4)}, ${parseFloat(coordinate[1]).toFixed(4)}`
  }
  
  return coordinate.toString()
}

// 获取枚举选项
const getEnumOptions = (type) => {
  const match = type.match(/enum\((.*)\)/i)
  if (match) {
    return match[1].split(',').map(option => 
      option.trim().replace(/^'|'$/g, '')
    )
  }
  return []
}

// 获取数字精度
const getPrecision = (type) => {
  if (type.toUpperCase().includes('DECIMAL')) {
    const match = type.match(/\(\d+,(\d+)\)/)
    return match ? parseInt(match[1]) : 2
  }
  return 0
}

// 获取最大长度
const getMaxLength = (type) => {
  const match = type.match(/\((\d+)\)/)
  return match ? parseInt(match[1]) : null
}

// 格式化数字
const formatNumber = (value) => {
  if (value === null || value === undefined) return ''
  return Number(value).toLocaleString()
}

// 格式化日期
const formatDate = (value) => {
  if (!value) return ''
  const date = new Date(value)
  return date.toLocaleString('zh-CN')
}

const loadTableData = async (searchParams = null) => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      region: route.query.region, // 加上区域过滤
      type: route.query.type      // 同时保留建筑类等类别过滤
    }

    // 保留原来的搜索逻辑
    if (searchParams && !searchParams.reset) {
      if (searchParams.quickSearch && searchParams.quickSearch.text) {
        params.search = searchParams.quickSearch.text
        params.searchField = searchParams.quickSearch.field || ''
      }
      
      if (searchParams.conditions && searchParams.conditions.length > 0) {
        params.advancedSearch = { conditions: searchParams.conditions }
      }
      
      currentSearchParams.value = searchParams
    } else if (searchParams && searchParams.reset) {
      currentSearchParams.value = null
    } else if (currentSearchParams.value) {
      const current = currentSearchParams.value
      if (current.quickSearch && current.quickSearch.text) {
        params.search = current.quickSearch.text
        params.searchField = current.quickSearch.field || ''
      }
      
      if (current.conditions && current.conditions.length > 0) {
        params.advancedSearch = { conditions: current.conditions }
      }
    }

    // 发请求时把 region/type 一起传过去
    const data = await apiService.getTableData(tableName.value, params)
    console.log('后端真实返回：', data) // 调试输出
    tableData.value = data.data || []
    columns.value = data.columns || []
    // total.value = data.total || 0
    total.value = Number(data.total) || 0


    if (advancedSearchRef.value) {
      advancedSearchRef.value.setSearchResult(total.value)
    }
    
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}


// 处理高级搜索
const handleAdvancedSearch = (searchParams) => {
  currentPage.value = 1
  loadTableData(searchParams)
}

// 刷新数据
const refreshData = () => {
  currentPage.value = 1
  currentSearchParams.value = null
  if (advancedSearchRef.value) {
    advancedSearchRef.value.resetSearch()
  }
  loadTableData()
}

// 导出搜索结果
const exportSearchResults = async () => {
  try {
    // 构建导出参数
    const params = {}
    
    if (currentSearchParams.value && !currentSearchParams.value.reset) {
      if (currentSearchParams.value.quickSearch && currentSearchParams.value.quickSearch.text) {
        params.search = currentSearchParams.value.quickSearch.text
        params.searchField = currentSearchParams.value.quickSearch.field || ''
      }
      
      if (currentSearchParams.value.conditions && currentSearchParams.value.conditions.length > 0) {
        params.advancedSearch = {
          conditions: currentSearchParams.value.conditions
        }
      }
    }
    
    // 获取所有匹配的数据（不分页）
    const data = await apiService.getTableData(tableName.value, { ...params, limit: 10000 })
    
    if (data.data && data.data.length > 0) {
      const blob = new Blob([JSON.stringify(data.data, null, 2)], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `${tableName.value}_search_results.json`
      a.click()
      URL.revokeObjectURL(url)
      ElMessage.success(`导出 ${data.data.length} 条搜索结果`)
    } else {
      ElMessage.warning('没有搜索结果可导出')
    }
  } catch (error) {
    console.error('导出搜索结果失败:', error)
    ElMessage.error('导出搜索结果失败')
  }
}

// 切换文件上传显示
const toggleFileUpload = () => {
  showFileUpload.value = !showFileUpload.value
}

// 处理文件上传成功
const handleUploadSuccess = (result) => {
  ElMessage.success(`文件导入成功：${result.successCount} 条记录`)
  refreshData()
}

// 分页处理
const handleSizeChange = () => {
  currentPage.value = 1
  loadTableData()
}

const handleCurrentChange = () => {
  loadTableData()
}

// 重置表单数据
const resetFormData = () => {
  Object.keys(formData).forEach(key => {
    delete formData[key]
  })
  
  editableColumns.value.forEach(column => {
    if (column.Type === 'tinyint(1)' || column.Type === 'boolean') {
      formData[column.Field] = false
    } else if (column.Field === '坐标') {
      formData.coordinate_lng = null
      formData.coordinate_lat = null
    } else {
      formData[column.Field] = null
    }
  })
}

// // 编辑记录  
// const editRecord = (record) => {
//   editingRecord.value = record
//   resetFormData()

//   // 填充表单数据
//   editableColumns.value.forEach(column => {
//     if (column.Field === '坐标') {
//       // 处理多种坐标格式
//       const coordinate = record[column.Field]
//       if (coordinate) {
//         // 处理{x,y}对象格式
//         if (typeof coordinate === 'object' && coordinate.x !== undefined && coordinate.y !== undefined) {
//           formData.coordinate_lng = parseFloat(coordinate.x)
//           formData.coordinate_lat = parseFloat(coordinate.y)
//         }
//         // 解析POINT格式
//         else if (typeof coordinate === 'string' && coordinate.includes('POINT')) {
//           const match = coordinate.match(/POINT\(([^)]+)\)/)
//           if (match) {
//             const coords = match[1].split(' ')
//             if (coords.length === 2) {
//               formData.coordinate_lng = parseFloat(coords[0])
//               formData.coordinate_lat = parseFloat(coords[1])
//             }
//           }
//         }
//         // 解析逗号分隔格式
//         else if (typeof coordinate === 'string' && coordinate.includes(',')) {
//           const coords = coordinate.split(',').map(Number)
//           if (coords.length === 2) {
//             formData.coordinate_lng = coords[0]
//             formData.coordinate_lat = coords[1]
//           }
//         }
//         // 解析数组格式
//         else if (Array.isArray(coordinate) && coordinate.length === 2) {
//           formData.coordinate_lng = coordinate[0]
//           formData.coordinate_lat = coordinate[1]
//         }
//       }
//     } else {
//       formData[column.Field] = record[column.Field]
//     }
//   })
  
//   showCreateDialog.value = true
// }
 
const editRecord = (record) => {
  editingRecord.value = record

  // 填充表单数据（只覆盖当前行对应的字段）
  editableColumns.value.forEach(column => {
    if (column.Field === '坐标') {
      const coordinate = record[column.Field]
      if (coordinate) {
        if (typeof coordinate === 'object' && coordinate.x !== undefined && coordinate.y !== undefined) {
          formData.coordinate_lng = parseFloat(coordinate.x)
          formData.coordinate_lat = parseFloat(coordinate.y)
        } else if (typeof coordinate === 'string' && coordinate.includes('POINT')) {
          const match = coordinate.match(/POINT\(([^)]+)\)/)
          if (match) {
            const coords = match[1].split(' ')
            if (coords.length === 2) {
              formData.coordinate_lng = parseFloat(coords[0])
              formData.coordinate_lat = parseFloat(coords[1])
            }
          }
        } else if (typeof coordinate === 'string' && coordinate.includes(',')) {
          const coords = coordinate.split(',').map(Number)
          if (coords.length === 2) {
            formData.coordinate_lng = coords[0]
            formData.coordinate_lat = coords[1]
          }
        } else if (Array.isArray(coordinate) && coordinate.length === 2) {
          formData.coordinate_lng = coordinate[0]
          formData.coordinate_lat = coordinate[1]
        }
      }
    } else {
      // 只覆盖当前行对应的字段，其他字段保留
      formData[column.Field] = record[column.Field]
    }
  })

  showCreateDialog.value = true
}


// 保存记录
const saveRecord = async () => {
  if (!formRef.value) return
  
  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) return
  
  saveLoading.value = true
  try {
    const data = { ...formData }

    // 处理地理坐标数据
    if (
      data.coordinate_lng !== null &&
      data.coordinate_lat !== null &&
      !isNaN(data.coordinate_lng) &&
      !isNaN(data.coordinate_lat)
    ) {
      // 设置经纬度字段，后端会处理 POINT 类型
      data['经度'] = data.coordinate_lng
      data['纬度'] = data.coordinate_lat
    }

    // 删除临时坐标字段
    delete data.coordinate_lng
    delete data.coordinate_lat

    // ✅ 强制注入所属区域和表类型（关键部分）
    const region = route.query.region || ''
    const type = route.query.type || ''
    data['所属区域'] = region
    data['表类型'] = type

    if (editingRecord.value) {
      const primaryKey = columns.value.find(col => col.Key === 'PRI')
      const id = editingRecord.value[primaryKey.Field]
      await apiService.updateRecord(tableName.value, id, data)
      ElMessage.success('记录更新成功')
    } else {
      await apiService.createRecord(tableName.value, data)
      ElMessage.success('记录创建成功')
    }

    showCreateDialog.value = false
    editingRecord.value = null
    loadTableData()
  } catch (error) {
    console.error('保存记录失败:', error)
    ElMessage.error('保存记录失败')
  } finally {
    saveLoading.value = false
  }
}


// 确认删除
const confirmDelete = (record) => {
  const primaryKey = columns.value.find(col => col.Key === 'PRI')
  const id = record[primaryKey.Field]
  
  ElMessageBox.confirm(
    `确定要删除这条记录吗？删除后无法恢复！`,
    '警告',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await apiService.deleteRecord(tableName.value, id)
      ElMessage.success('记录删除成功')
      loadTableData()
    } catch (error) {
      console.error('删除记录失败:', error)
      ElMessage.error('删除记录失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 导出数据
const exportData = async () => {
  try {
    ElMessage.info('正在导出数据，请稍候...') // 增加加载提示
    const data = await apiService.exportTable(tableName.value)
    
    // 验证数据有效性
    if (!data || (Array.isArray(data) && data.length === 0)) {
      ElMessage.warning('没有数据可导出')
      return
    }
    
    // 处理 Blob 或 JSON 数据（兼容不同后端返回格式）
    let blob
    if (data instanceof Blob) {
      blob = data
    } else {
      // 确保 JSON 序列化正确
      blob = new Blob(
        [JSON.stringify(data, null, 2)], 
        { type: 'application/json;charset=utf-8;' }
      )
    }
    
    // 下载逻辑
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `${tableName.value}_export_${new Date().getTime()}.json` // 增加时间戳避免重名
    document.body.appendChild(a)
    a.click()
    
    // 延迟清理，确保下载完成
    setTimeout(() => {
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
    }, 100)
    
    ElMessage.success('数据导出成功')
  } catch (error) {
    console.error('导出失败详情:', error) // 打印完整错误信息
    let errorMsg = '导出数据失败'
    if (error.response) {
      // 根据状态码提示具体原因
      if (error.response.status === 404) {
        errorMsg += '（接口不存在，请检查地址）'
      } else if (error.response.status === 500) {
        errorMsg += '（服务器错误，请联系管理员）'
      } else if (error.response.status === 403) {
        errorMsg += '（没有导出权限）'
      }
    } else if (error.message.includes('Failed to fetch')) {
      errorMsg += '（网络连接失败，请检查网络）'
    }
    ElMessage.error(errorMsg)
  }
}

// 导入前处理
const beforeImport = (file) => {
  const reader = new FileReader()
  reader.onload = async (e) => {
    try {
      const data = JSON.parse(e.target.result)
      if (!Array.isArray(data)) {
        ElMessage.error('导入文件格式错误，应为JSON数组')
        return
      }
      
      // 前端预处理：过滤空值和主键字段（与后端呼应）
      const filteredData = data.map(item => {
        const filtered = {}
        Object.entries(item).forEach(([key, value]) => {
          // 过滤空值
          if (value === null || value === undefined || value === '') return
          
          // 过滤主键字段（假设主键字段包含'id'或'编号'）
          if (key.toLowerCase().includes('id') || key.includes('编号')) return
          
          // 坐标格式处理：支持"116.12,39.94"格式
          if ((key.includes('坐标') || key === 'coordinates') && typeof value === 'string') {
            const [lng, lat] = value.split(',').map(Number)
            if (!isNaN(lng) && !isNaN(lat)) {
              filtered['经度'] = lng
              filtered['纬度'] = lat
              return
            }
          }
          // 坐标格式处理：对{x,y}对象格式的支持
          if ((key.includes('坐标') || key === 'coordinates')) {
            if (typeof value === 'object' && value.x !== undefined && value.y !== undefined) {
              filtered['经度'] = value.x
              filtered['纬度'] = value.y
              return
            } else if (typeof value === 'string') {
              const [lng, lat] = value.split(',').map(Number)
              if (!isNaN(lng) && !isNaN(lat)) {
                filtered['经度'] = lng
                filtered['纬度'] = lat
                return
              }
            }
          }
          filtered[key] = value
        })
        return filtered
      })
      
      const result = await apiService.importTable(tableName.value, filteredData)
      ElMessage.success(`导入完成：成功 ${result.successCount} 条，失败 ${result.errorCount} 条`)
      
      // 展示导入错误详情
      if (result.errors && result.errors.length > 0) {
        ElMessageBox.alert(
          `<div>
            <p>错误详情 (前${Math.min(result.errors.length, 10)}条):</p>
            <ul style="max-height: 200px; overflow-y: auto; padding-left: 20px;">
              ${result.errors.slice(0, 10).map((err, i) => 
                `<li>${i+1}. ${err}</li>`
              ).join('')}
            </ul>
          </div>`,
          '导入错误',
          { dangerouslyUseHTMLString: true }
        )
      }
      
      loadTableData()
    } catch (error) {
      console.error('导入数据失败:', error)
      ElMessage.error('导入数据失败：' + (error.message || '格式错误或网络问题'))
    }
  }
  reader.readAsText(file)
  return false // 阻止默认上传行为
}

// 监听表名变化
watch(tableName, () => {
  currentPage.value = 1
  currentSearchParams.value = null
  showFileUpload.value = false
  loadTableData()
}, { immediate: true })

// 监听对话框关闭
watch(showCreateDialog, (val) => {
  if (!val) {
    editingRecord.value = null
    resetFormData()
  } else {
    resetFormData()
  }
})

//过滤
onMounted(() => {
  const region = route.query.region
  const type = route.query.type
  const tableName = decodeURIComponent(route.params.tableName)

  console.log('当前数据页：', tableName)
  console.log('所属区域：', region)
  console.log('类别：', type)

  // 在这里根据 region 和 type 过滤数据
  loadFilteredData(tableName, region, type)
})
const loadFilteredData = async (tableName, region, type) => {
  loading.value = true
  try {
    // 调用接口时把 region 和 type 一起传给后端
    const res = await apiService.getTableData(tableName, { region, type })

    tableData.value = res.data || []

    ElMessage.success(`已加载 ${region} 的 ${type} 数据`)
  } catch (err) {
    console.error('加载数据失败:', err)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}
// 返回表页
// const goBackToEditPage = () => {
//   window.history.back()
// }


const goBackToTablesPage = () => {
  const region = route.query.region
  const type = route.query.type
  if (!region || !type) {
    ElMessage.warning('缺少必要参数，无法返回表页')
    return
  }
  router.push(`/tables?region=${region}&type=${type}`)
}

//点击编辑按钮后，编辑框的回显效果




</script>

<style scoped>
.back-card {
  display: flex;
  align-items: center;
  cursor: pointer;
  background-color: #f5f7fa;
  border-radius: 12px;
  padding: 8px 16px;
  width: fit-content;
  /* margin-bottom: -10px; */
  margin-top: -50px;
  transition: all 0.2s ease;
  box-shadow: 0 10px 10px rgba(0, 0, 0, 0.08);
}

.back-card:hover {
  background-color: #ecf5ff;
  transform: translateY(-1px);
}

.back-icon {
  margin-right: 8px;
  color: #2687e9;
  font-size: 18px;
}

.back-text {
  font-weight: 500;
  color: #000000;
  font-size: 20px;
}

.data-management {
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  justify-content: flex-end;
}

.page-description {
  margin: 0;
  text-align: right; 
  color: #909399;
  font-size: 14px;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
}

.action-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.page-info {
  color: #909399;
  font-size: 14px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.cell-content {
  display: flex;
  align-items: center;
}

.coordinate-input {
  width: 100%;
}

.upload-demo {
  display: inline-block;
}

:deep(.el-upload) {
  display: inline-block;
}

:deep(.el-table .cell) {
  padding: 8px 0;
}

@media (max-width: 768px) {
  .action-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .action-left {
    justify-content: center;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}

</style>